﻿using System;
using System.Runtime.Caching;

namespace blackhouse.WebNemo.Data.Cache
{

    public static class MemoryCacheExtensions
    {

        public static T GetOrCreate<T>(this MemoryCache memoryCache, string cacheKey, Func<T> callback, Func<int[]> cacheBasedOn, int slidingExpirationInMinutes = 20)
            where T : class {
            T result = null;
            if (memoryCache.Contains(cacheKey))
                result = memoryCache[cacheKey] as T;
            if (result != null) return result;
            result = callback();
            if (result == null) return null;
            var ci = new CacheItem(cacheKey, result);
            var cip = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(slidingExpirationInMinutes) };
            var basedOn = cacheBasedOn();
            if (basedOn != null && basedOn.Length > 0)
                cip.ChangeMonitors.Add(new NemoChangeMonitor(cacheBasedOn()));
            memoryCache.Add(ci, cip);
            return result;
        }

    }
}
